package com.example.sunnyweather.logic.network

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

/**
 * 这是一个单例类  对网络请求的API进行封装 相当于是所有网络数据源访问的入口  写完了吗
 * */
object SunnyWeatherNetwork {

    private val placeService = ServiceCreator.create<PlaceService>()
    private val weathereService = ServiceCreator.create(WeathereService::class.java)

    suspend fun searchPlaces(query:String) = placeService.searchPlaces(query).await()

    suspend fun getDailyWeather(lng:String,lat:String) = weathereService.getDailyWeather(lng,lat).await()

    suspend fun geteRealtimeWather(lng:String,lat:String) = weathereService.getRealtimeWeather(lng,lat).await()




    private suspend fun <T> Call<T>.await():T{
        return suspendCoroutine { continuation ->
            enqueue(object:Callback<T>{
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body != null) continuation.resume(body)
                    else continuation.resumeWithException(RuntimeException("response body is null"))
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }
            })
        }
    }

}